package org.example.kg_back.service.imp;

import org.example.kg_back.PoJo.DTO.LoginUserDetails;
import org.example.kg_back.PoJo.VO.LoginVO;
import org.example.kg_back.PoJo.VO.TokenVo;
import org.example.kg_back.service.LoginService;
import org.example.kg_back.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImp implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public TokenVo login(LoginVO loginVO) {
        Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginVO.getAccount(), loginVO.getPassword()));
        if (authenticate == null){
            throw new RuntimeException("账号密码错误");
        }
        LoginUserDetails principal = (LoginUserDetails) authenticate.getPrincipal();
        String jwt = JwtUtil.createJWT(principal.getSysUser().getAccount());
        return new TokenVo(jwt);
    }
}
